#include "const.h"
#include <iostream>
#include <thread>
#include "boost/asio.hpp"


using boost::asio::ip::tcp;



//构建两个线程，一个用于读取数据，一个用于发送数据


int main()
{
    try
    {

        boost::asio::io_context io_context;
        boost::asio::ip::tcp::socket socket(io_context);
        socket.connect(tcp::endpoint(boost::asio::ip::address::from_string("192.168.248.171"), 8888));
        //同步发送数据
        std::thread write_thread([&socket]()
        {
            while(1)
            {
                const char * sendData="hello world";
                char sendBuf[MAX_LENGTH]={0};
                short len = boost::asio::detail::socket_ops::host_to_network_short(strlen(sendData));
                memcpy(sendBuf,&len,HEAD_LENGTH);
                memcpy(sendBuf+HEAD_LENGTH,sendData,strlen(sendData));
                boost::asio::write(socket,boost::asio::buffer(sendBuf,HEAD_LENGTH+strlen(sendData)));
                std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                
            }
        });
        //同步接收数据
        std::thread read_thread([&socket]()
        {
            while(1)
            {
                char receiveHead[HEAD_LENGTH]={0};
                boost::asio::read(socket,boost::asio::buffer(receiveHead,HEAD_LENGTH));
                short msgLen=0;
                memcpy(&msgLen,receiveHead,HEAD_LENGTH);
                msgLen=boost::asio::detail::socket_ops::network_to_host_short(msgLen);
                char msg[MAX_LENGTH]={0};
                boost::asio::read(socket,boost::asio::buffer(msg,msgLen));
                std::cout<<"recv msg len = "<<msgLen<<std::endl;
                std::cout<<"recv msg = "<<msg<<std::endl;
                
                std::this_thread::sleep_for(std::chrono::milliseconds(950));
            }
        });


        //等待两个线程结束
        write_thread.join();
        read_thread.join();

        io_context.run();
        
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

}
